package parser;

import lexer.TokenType;

/**
 * Holds the logic determining whether an expression should be parsed as a
 * Primary Expression or a Binary Expression Required since LogoExpression is an
 * abstract type, so it's not possible to go new LogoExpression(tokeniterator)
 */
public class LogoExpressionParser {

	/**
	 * Parses an Expression from the TokenIterator
	 * 
	 * @param it
	 * @return LogoPrimaryExpression or LogoBinaryExpression depending on
	 *         upcoming tokens
	 * @throws LogoParseException
	 */
	public static LogoExpression parseExpression(TokenIterator it) throws LogoParseException {
		if (!it.hasNext()) {
			throw new LogoParseException("Unexpectedly reached end of program");
		}
		TokenType type = it.peek().getType();

		if (type == TokenType.IDENTIFIER || type == TokenType.NUMBER) {
			if (it.matchNextTokenAndOperator(type)) {
				return new LogoBinaryExpression(it);
			} else {
				return new LogoPrimaryExpression(it);
			}
		}

		throw new LogoParseSyntaxException(it.next(),
				"IDENTIFIER or NUMBER (Expression)");
	}
}
